import time
import random
import threading
from iClouds.libs import header_has_guuid


class baseUnity(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.isRun = True
        self.status = "fight"

    def stop(self):
        self.isRun = False


class zombie(baseUnity):
    """僵尸: 房间,轨道,序号, 道具"""

    def __init__(self, room, track, index, tool=0):
        super().__init__()
        self.room = room
        self.guid = header_has_guuid()
        self.track = track  # 轨道
        self.index = index  # 僵尸序号
        self.tool = tool  # 道具序号
        self.point = 9  # x位置
        self.speed = 3  # 攻击间隔
        self.power = [0, 0]  # 火力
        self.last = time.time()

    def __del__(self):
        try:
            self.room.zombie.remove(self)
        except:
            pass

    def run(self):
        print(f"初始化僵尸 {self.track} {self.guid}")
        self.room.alertAIring(
            {
                "act": "newZombie",
                "guid": "room",
                "code": 200,
                "data": {
                    "tract": self.track,
                    "index": self.index,
                    "tool": self.tool,
                    "guid": self.guid,
                },
            }
        )
        while self.isRun:
            time.sleep(1)
            if self.status == "death":
                break
            if self.point == 0 and time.time() - self.last > self.speed:
                fire = random.choice(range(self.power))
                self.room.hp -= fire
                self.last = time.time()
                self.room.alertAIring(
                    {"act": "health", "guid": "room", "code": 200, "data": self.room.hp}
                )

    def setTools(self, tool):
        """设置道具"""
        self.tool = tool

    def setPoint(self, point):
        """设置位置"""
        self.point = point

    def setSpeed(self, speed):
        """攻击速度"""
        self.speed = speed

    def setPower(self, power):
        """火力"""
        self.power = power
